package com.example.demo.action.client;/**
 * Created by kete on 2018-11-30.
 */

import com.alibaba.fastjson.JSON;
import com.example.demo.action.common.CustomProtocol;
import com.example.demo.action.common.HeartBeatEncode;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 作者：kete
 * 创建时间：2018-11-30 16:43
 * 功能描述：
 * 版本：
 */
@Component
public class HeartBeatClient {
    private final static Logger logger = LoggerFactory.getLogger(HeartBeatClient.class);

    @Value("${netty.server.port}")
    private int nettyPort;

    @Value("${netty.server.host}")
    private String host;

    private NioEventLoopGroup work = new NioEventLoopGroup();

    private SocketChannel channel;

    @PostConstruct
    public void staet() throws Exception{
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(work)
                .channel(NioSocketChannel.class)
                .handler(new CustomerHandleInitializer());

        ChannelFuture future = bootstrap.connect(host, nettyPort).sync();

        if (future.isSuccess()) {
            logger.info("启动 Netty 成功");
        }
        channel = (SocketChannel) future.channel();

    }

    public void sendMsg(CustomProtocol customProtocol) {
        ChannelFuture future = channel.writeAndFlush(customProtocol);
        future.addListener((ChannelFutureListener) channelFuture ->
                logger.info("客户端手动发消息成功={}", JSON.toJSONString(customProtocol)));

    }


    public class CustomerHandleInitializer extends ChannelInitializer<Channel> {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline()
                    //10 秒没发送消息 将IdleStateHandler 添加到 ChannelPipeline 中
                    .addLast(new IdleStateHandler(0, 10, 0))
                    .addLast(new HeartBeatEncode())
                    .addLast(new EchoClientHandler())
            ;
        }
    }
}
